import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.UUID;

public class PaymentService {
    private UserService userService;
    private PaymentOrderRepository paymentOrderRepository;
    
    public PaymentService() {
        this.userService = new UserService();
        this.paymentOrderRepository = new PaymentOrderRepository();
    }
    
    public PaymentOrder createOrder(Long userId, BigDecimal amount, String paymentType) {
        // 验证参数
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("支付金额必须大于0");
        }
        
        if (!isValidPaymentType(paymentType)) {
            throw new IllegalArgumentException("不支持的支付类型");
        }
        
        // 创建支付订单
        PaymentOrder order = new PaymentOrder();
        order.setOrderNo(generateOrderNo());
        order.setUserId(userId);
        order.setAmount(amount);
        order.setPaymentType(paymentType);
        order.setStatus("PENDING");
        order.setCreateTime(LocalDateTime.now());
        
        // 保存订单
        return paymentOrderRepository.save(order);
    }
    
    public boolean handlePaymentCallback(String orderNo, String transactionId, String status) {
        PaymentOrder order = paymentOrderRepository.findByOrderNo(orderNo);
        if (order == null) {
            return false;
        }
        
        // 更新订单状态
        order.setTransactionId(transactionId);
        order.setStatus(status);
        order.setPayTime(LocalDateTime.now());
        
        // 如果支付成功，更新用户余额
        if ("SUCCESS".equals(status)) {
            userService.updateBalance(order.getUserId(), order.getAmount());
        }
        
        paymentOrderRepository.save(order);
        return true;
    }
    
    public PaymentOrder getOrderByOrderNo(String orderNo) {
        return paymentOrderRepository.findByOrderNo(orderNo);
    }
    
    private String generateOrderNo() {
        return "PAY" + UUID.randomUUID().toString().replace("-", "").substring(0, 28);
    }
    
    private boolean isValidPaymentType(String paymentType) {
        return "WECHAT".equals(paymentType) || 
               "ALIPAY".equals(paymentType) || 
               "BANK_CARD".equals(paymentType);
    }
}